# -*- coding: utf-8 -*-

"""
@Datetime: 2019/1/1
@Author: Zhang Yafei
"""
from flask import Blueprint, redirect, request, make_response, jsonify, url_for
from sqlalchemy import or_

from BeautifulData.forms import LoginForm
from common.libs.helper import ops_render, getCurrentDate
from common.libs.UserService import UserService
from common.models.models import User, AppAccessLog
from application import app, db
from common.libs.UrlManager import UrlManager
from common.utils.pagination import Pagination


route_account = Blueprint('account_page', __name__)


@route_account.route('/login', methods=['GET','POST'])
def login():
    """
    账户登录
    :return:
    """
    if request.method == 'GET':
        form = LoginForm()
        return ops_render('login.html', {'form':form})
    form = LoginForm(request.form)
    if form.validate():
        user_info = User.query.filter_by(login_name=form.data['username']).first()
        response = make_response(redirect('/home'))
        response.set_cookie(app.config['AUTH_COOKIE_NAME'], '%s#%s'%(UserService.genAuthCode(user_info), user_info.id), 60 * 60 * 24 * 120)  # 保存120天
        return response
    return ops_render('login.html',{'form': form})


@route_account.route('/logout')
def logout():
    """
    账户退出
    :return:
    """
    response = make_response(redirect(UrlManager.buildUrl('/user/login')))
    response.delete_cookie(app.config['AUTH_COOKIE_NAME'])
    return response


@route_account.route('/index')
def index():
    resp = {}
    req = request.values
    page = int(req['p']) if('p' in req and req['p']) else 1
    query = User.query
    if 'mix_kw' in req:
        rule = or_(User.nickname.ilike('%{0}%'.format(req['mix_kw'])), User.mobile.ilike('%{0}%'.format(req['mix_kw'])))
        query = query.filter(rule)
    if 'status' in req and int(req['status']) > -1:
        query = query.filter(User.status == int(req['status']))
    page_obj = Pagination(query.count(), request.args.get('p'))
    page_str = page_obj.page_str(base_url=url_for('account_page.index'))
    data_list = query.order_by(User.id.desc()).all()[page_obj.start:page_obj.end]
    resp['page_obj'] = page_obj
    resp['page_str'] = page_str
    resp['data_list'] = data_list
    resp['search_con'] = req
    resp['status_mapping'] = app.config['STATUS_MAPPING']
    return ops_render('account/index.html', resp)


@route_account.route('/info')
def info():
    resp = {}
    req = request.args
    id = int(req.get('id', 0))
    reback_url = UrlManager.buildUrl('/account/index')
    if id < 1:
        return redirect(reback_url)
    info = User.query.filter_by(id=id).first()
    if not info:
        return redirect(reback_url)
    resp['info'] = info
    error_log = AppAccessLog.query.filter_by(uid=id).limit(5).all()
    resp['error_log'] = error_log
    return ops_render('account/info.html', resp)


@route_account.route('/set', methods=['GET','POST'])
def set():
    defalut_pwd = '******'
    if request.method == 'GET':
        resp = {}
        req = request.args
        uid = int(req.get('id', 0))
        info = None
        if uid:
            info = User.query.filter_by(id=uid).first()
        resp['info'] = info
        return ops_render('account/set.html', resp)
    resp = {'code':200, 'msg':'操作成功~~', 'data':{}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    nickname = req['nickname'] if 'nickname' in req else ''
    mobile = req['mobile'] if 'mobile' in req else ''
    email = req['email'] if 'email' in req else ''
    login_name = req['login_name'] if 'login_name' in req else ''
    login_pwd = req['login_pwd'] if 'login_pwd' in req else ''

    if nickname is None or len(nickname) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的姓名'
        return jsonify(resp)

    if mobile is None or len(mobile) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的手机号'
        return jsonify(resp)

    if email is None or len(email) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的邮箱'
        return jsonify(resp)

    if login_name is None or len(login_name) < 1:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的用户名'
        return jsonify(resp)

    if login_pwd is None or len(login_pwd) < 6:
        resp['code'] = -1
        resp['msg'] = '请输入符合规范的密码'
        return jsonify(resp)
    has_in = User.query.filter(User.login_name == login_name, User.id != id).first()
    if has_in:
        resp['code'] = -1
        resp['msg'] = '该登录名已存在，请换一个试试~~'
        return jsonify(resp)
    user_info = User.query.filter_by(id=id).first()
    if user_info:
        model_user = user_info
    else:
        model_user = User()
        model_user.created_time = getCurrentDate()
        model_user.login_salt = UserService.geneSalt()
    model_user.nickname = nickname
    model_user.mobile = mobile
    model_user.email = email
    model_user.login_name = login_name
    if login_pwd != defalut_pwd:
        model_user.login_pwd = UserService.genePwd(login_pwd, model_user.login_salt)
    model_user.updated_time = getCurrentDate()

    db.session.add(model_user)
    db.session.commit()
    return jsonify(resp)


@route_account.route('/ops', methods=['GET', 'POST'])
def ops():
    resp = {'code':200, 'msg':'操作成功~~', 'data':{}}
    req = request.values
    id = req['id'] if 'id' in req else 0
    act = req['act'] if 'act' in req else ''
    if not id:
        resp['code'] = -1
        resp['msg'] = '请选择要操作的账号~~'
        return jsonify(resp)

    if act not in ['remove', 'recover']:
        resp['code'] = -1
        resp['msg'] = '操作有误，请重试~~'
        return jsonify(resp)

    user_info = User.query.filter_by(id=id).first()
    if not user_info:
        resp['code'] = -1
        resp['msg'] = '指定账号不存在~~'
        return jsonify(resp)
    if act == 'remove':
        user_info.status = 0
    elif act == 'recover':
        user_info.status = 1

    user_info.update_time = getCurrentDate()
    db.session.add(user_info)
    db.session.commit()
    return jsonify(resp)